package com.lagou.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lagou.search.dto.EsOrderQueryDTO;
import com.lagou.search.entity.Order;
import com.lagou.search.entity.es.EsOrder;
import com.lagou.search.manager.IEsOrderManager;
import com.lagou.search.manager.IOrderManager;
import com.lagou.search.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单服务类
 * @author yzh
 * @since 2021/12/2
 **/
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private IOrderManager orderManager;

    @Autowired
    private IEsOrderManager esOrderManager;

    @Override
    public List<EsOrder> list(EsOrderQueryDTO esOrderQueryDTO) {
        return esOrderManager.list(esOrderQueryDTO);
    }

    @Override
    public void save(Order order) {
        orderManager.saveWithEs(order);
    }

    @Override
    public void remove(Long id) {
       orderManager.removeWithEs(id);
    }

    @Override
    public void syncToEs() {
        //1.查询MySQL中所有的数据
        long orderCountNum = orderManager.count();
        if(orderCountNum == 0) {
            return;
        }

        //2.进行分批数据同步
        //每批最大同步数
        int maxSyncNum = 1000;
        //需要同步的批数
        int batchNum = new BigDecimal(orderCountNum).divide(new BigDecimal(maxSyncNum), RoundingMode.CEILING).intValue();
        //分页对象
        IPage<Order> page = new Page<>();
        page.setSize(maxSyncNum);
        for (int i = 1; i <= batchNum; i++) {
            page.setCurrent(i);
            //分页查询MySQL中的数据
            IPage<Order> currentPage = orderManager.page(page);
            List<EsOrder> currentEsOrders = currentPage.getRecords().stream().map(order -> {
                EsOrder esOrder = new EsOrder();
                BeanUtils.copyProperties(order, esOrder);
                return esOrder;
            }).collect(Collectors.toList());
            //同步保存到ES中
            esOrderManager.saveBatch(currentEsOrders);
        }
    }

}